//
//  AXFAddressManager.m
//  AIXF
//
//  Created by zhanghui on 2017/7/13.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "AXFAddressManager.h"

@implementation AXFAddressManager

IMPLEMENTATION_SINGLETON(AXFAddressManager);

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        //监听属性的变化
        [self addObserver:self forKeyPath:@"type" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

#pragma mark - 新建地址
- (void)addNewAddressAction:(AXFMyAddressModel *)model{
    
    //添加新的地址
    [self.addressList addObject:model];
    
    NSLog(@"%@--%zd",self.addressList,self.addressList.count);
    
    self.type = AddressMangagerTypeAdd;
    
}

#pragma mark - 删除地址
- (void)deleteAddressAction:(NSUInteger )index{
    
    //删除地址
    [self.addressList removeObjectAtIndex:index];
    
    self.type = AddressMangagerTypeAddRemove;
}

#pragma mark - 把cell插入最上面
- (void)insertTopAction:(AXFMyAddressModel *)model{
    
    [self.addressList removeObject:model];
    
    [self.addressList insertObject:model atIndex:0];
    
    self.type = AddressMangagerTypeAddInsertFornt;
}


- (NSMutableArray<AXFMyAddressModel *> *)addressList{
    
    if (!_addressList) {
        
      _addressList  = [NSMutableArray array];
    }
    
    return _addressList;
    
}

#pragma mark - 实现监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    //发送通知
    [[NSNotificationCenter defaultCenter]postNotificationName:AddressListDidChangeNotifation object:self];
    
}

#pragma mark - 归档
- (void)addressListArchiver{
    
   
    [NSKeyedArchiver archiveRootObject:self.addressList toFile:ArchiverPath];
    
}

#pragma mark - 接档
- (id)addressListUnArchiver{

    //接档
    NSArray<AXFMyAddressModel *> *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:ArchiverPath];
    
    return arr;
}




@end
